import promoai
from other.save_bpmn_and_parse import save_bpmn_and_parse
import json
import requests
from other.merge_and_remove_multiple_states import deduplicate_rows

def generate_model_and_sequence(description, api_key, ai_model, provider, webhook_url):
    """
    封装模型生成逻辑，返回结果字典，不直接操作 st.session_state 或 st.status
    """
    try:
        # 调用大模型生成流程
        process_model = promoai.generate_model_from_text(
            description,
            api_key=api_key,
            ai_model=ai_model,
            ai_provider=provider,
        )

        # 保存 BPMN 并解析
        sequence_df, sequence_json = save_bpmn_and_parse(process_model)

        # 调用 webhook
        payload = {
            "sequence_feedback": [],
            "sequence_json": json.dumps(sequence_json, ensure_ascii=False, indent=2),
            "description": description
        }
        response = requests.post(webhook_url, json=payload)

        # 去重
        sequence_json = deduplicate_rows(
            json.loads(response.text)["workflow_list"]
        )

        return {
            "success": True,
            "process_model": process_model,
            "sequence_df": sequence_df,
            "sequence_json": sequence_json,
            "error": None
        }

    except Exception as e:
        return {
            "success": False,
            "process_model": None,
            "sequence_df": None,
            "sequence_json": None,
            "error": str(e)
        }
